<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Category extends BaseModel
{
    protected $fillable = ['name', 'type', 'status','icon' ,'parent_id','sort', 'description'];


    /**
     * 图标地址
     */
    protected function icon(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value ? asset($value) : '',
            set: fn ($value) => normalizePath($value)
        );
    }

    /**
     * 获取子分类
     */
    public function children()
    {
        return $this->hasMany(Category::class,'parent_id');
    }

    /**
     * 获取所有的子分类（递归）
     */
    public function allChildren()
    {
        return $this->children()->with('allChildren');
    }

    /**
     * 获取当前分类及所有子分类的ID
     */
    public function allChildIds()
    {
        return $this->allChildren()->get()->pluck('id');
    }

    /**
     * 获取父分类
     */
    public function parent()
    {
        return $this->belongsTo(Category::class,'parent_id');
    }

    /**
     * 获取所有的祖先分类（递归）
     */
    public function ancestors()
    {
        return $this->parent()->with('ancestors');
    }


    /**
     * 获取列表数据
     * @param $params
     */
    public static function getQueryData($params = [])
    {
        return self::query()->when($params['name'] ?? '',function($query,$value){
            return $query->where('name','like','%'.$value.'%');
        })->when($params['status'] ?? '',function($query,$value){
            return $query->where('status',$value);
        })->when($params['type'] ?? '',function($query,$value){
            return $query->where('type',$value);
        })->when($params['parent_id'] ?? '',function($query,$value){
            return $query->where('parent_id',$value);
        })
            ->with('allChildren')->whereNull('parent_id')
            ->latest('id')->paginate(request('pageSize',20))->toArray();
    }
}
